package cn.spiral.user.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;

import cn.spiral.core.action.BaseAction;
import cn.spiral.core.utils.QueryHelper;
import cn.spiral.role.entity.Role;
import cn.spiral.role.service.RoleService;
import cn.spiral.user.entity.User;
import cn.spiral.user.entity.UserRole;
import cn.spiral.user.service.UserService;
import net.sf.json.JSONObject;

public class UserAction extends BaseAction {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	private List<User> userList;
	private User user;
	//用于收集角色集
	private String[] userRoleIds;
	
	private String searchName="";
	
	//注意，file并不是指前端jsp上传过来的文件本身，而是文件上传过来存放在临时文件夹下面的文件
	private File headImg;
	private String headImgContentType;
	//file标签中name属性拼接上FileName就是文件名称
	private String headImgFileName;
	//导入excel文件
	private File userExcel;
	private String userExcelContentType;
	private String userExcelFileName;
	
	//返回json用的
	private String result;

	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	//列表页面
	public String listUI(){
		//自动装入栈中
		QueryHelper queryHelper=new QueryHelper(User.class, "u");
		try {
			searchName=URLDecoder.decode(searchName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		queryHelper.addCondition("u.name like ?", "%"+searchName+"%");
		pageResult = userService.getPageResult(queryHelper, super.getPageNo(), super.getPageSize());
		return "listUI";
	}
	//跳转到新增页面
	public String addUI(){
		//查询数据库中现有的所有角色类型用于在jsp页面显示
		List<Role> roleObjects = roleService.findObjects();
		ActionContext.getContext().getContextMap().put("roleList", roleObjects);
		return "addUI";
	}
	//保存新增
	public String add(){
		if(user != null){
			
			//将上传到临时文件夹中的文件重新保存到指定路径
			if(headImg!=null){
				//获得文件后缀名称
				String endFix=headImgFileName.substring(headImgFileName.lastIndexOf(".")-1);
				//获得upload文件夹路径
				String filePath=ServletActionContext.getServletContext().getRealPath("upload/user");
				//用uuid重命名图片名称
				String newFilename=UUID.randomUUID().toString().replace("-", "")+endFix;
				try {
					FileUtils.copyFile(headImg, new File(filePath, newFilename));
				} catch (IOException e) {
					e.printStackTrace();
				}
				//设置头像路径
				user.setHeadImg("user/"+newFilename);
			}
			userService.saveUserAndRole(user,userRoleIds);
		}
		return "list";
	}
	//跳转到编辑页面
	public String editUI(){
		ActionContext.getContext().getContextMap().put("roleList", roleService.findObjects());
		if (user != null && user.getId() != null) {
			//查找该用户详细信息
			user = userService.findObjectById(user.getId());
			
			//查询该用户拥有的角色
			List<UserRole> list = userService.getUserRolesByUserId(user.getId());
			if(list != null && list.size() > 0){
				userRoleIds = new String[list.size()];
				for(int i = 0; i < list.size(); i++){
					userRoleIds[i] = list.get(i).getId().getRole().getRoleId();
				}
			}
		}
		return "editUI";
	}
	//保存编辑
	public String edit(){
		if(user != null){
			if(headImg!=null){
				//获得文件后缀名称
				String endFix=headImgFileName.substring(headImgFileName.lastIndexOf("."));
				//获得upload文件夹路径
				String filePath=ServletActionContext.getServletContext().getRealPath("upload/user");
				//用uuid重命名图片名称
				String newFilename=UUID.randomUUID().toString().replace("-", "")+endFix;
				try {
					FileUtils.copyFile(headImg, new File(filePath, newFilename));
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(user.getHeadImg()!=null){
					//先删除原本的头像图片
					String oldPath=filePath.substring(0,filePath.lastIndexOf('\\'));
					File oldHeadImg=new File(oldPath,user.getHeadImg());
					if(oldHeadImg.exists())
						oldHeadImg.deleteOnExit();
				}				
				//设置头像路径
				user.setHeadImg("user/"+newFilename);
			}
			userService.updateUserAndRole(user,userRoleIds);
		}
		return "list";
	}
	//删除
	public String delete(){
		if(user != null && user.getId() != null){
			userService.delete(user.getId());
		}
		return "list";
	}
	//批量删除
	public String deleteSelected(){
		if(selectedRow != null){
			for(String id: selectedRow){
				userService.delete(id);
			}
		}
		return "list";
	}
	
	//导出用户列表
	public void exportExcel(){
		try {
			//查询出所有用户列表
			userList =userService.findObjects();
			//获得response对象，执行提示下载
			HttpServletResponse response=ServletActionContext.getResponse();
			//说明是excel文件
			response.setContentType("application/x-excel");
			//设置header，对文件名进行中文转码防止出现乱码
			response.setHeader("Content-Disposition", "attachement;filename="+new String("用户列表.xls".getBytes(),"ISO-8859-1"));
			ServletOutputStream outputStream=response.getOutputStream();
			userService.exportExcel(userList,outputStream);
			//如果前端没有关闭输出流，则关闭
			if(outputStream!=null){
				outputStream.close();	
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//导入用户列表
	public String importExcel(){
		if(userExcel!=null){
			
			//用正则表达式判断是否为excel文件
			//^$分别代表开始和结束， “.”代表任意字符,“\\.”代表.  "?i"代表无视大小写
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
				//导入
				userService.importExcel(userExcel,userExcelFileName);
			}
		}
		return "list";
	}
	
	//校验账号唯一性
	public String verifyAccount(){
		try {
			if(user != null && StringUtils.isNotBlank(user.getAccount())){
				//根据帐号到数据库中校验是否存在该帐号对应的用户
				List<User> list = userService.findUserByAccountAndId(user.getId(), user.getAccount());
				String unique = "true";
				if(list != null && list.size() > 0){
					unique = "false";
				}
				
				Map<String, Object> resultMap=new HashMap<String, Object>();
				resultMap.put("unique", unique);
				result=JSONObject.fromObject(resultMap).toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String[] getSelectedRow() {
		return selectedRow;
	}
	public void setSelectedRow(String[] selectedRow) {
		this.selectedRow = selectedRow;
	}
	public File getHeadImg() {
		return headImg;
	}
	public void setHeadImg(File headImg) {
		this.headImg = headImg;
	}
	public String getHeadImgContentType() {
		return headImgContentType;
	}
	public void setHeadImgContentType(String headImgContentType) {
		this.headImgContentType = headImgContentType;
	}
	public String getHeadImgFileName() {
		return headImgFileName;
	}
	public void setHeadImgFileName(String headImgFileName) {
		this.headImgFileName = headImgFileName;
	}
	public File getUserExcel() {
		return userExcel;
	}
	public void setUserExcel(File userExcel) {
		this.userExcel = userExcel;
	}
	public String getUserExcelContentType() {
		return userExcelContentType;
	}
	public void setUserExcelContentType(String userExcelContentType) {
		this.userExcelContentType = userExcelContentType;
	}
	public String getUserExcelFileName() {
		return userExcelFileName;
	}
	public void setUserExcelFileName(String userExcelFileName) {
		this.userExcelFileName = userExcelFileName;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	public String[] getUserRoleIds() {
		return userRoleIds;
	}
	public void setUserRoleIds(String[] userRoleIds) {
		this.userRoleIds = userRoleIds;
	}
	public String getSearchName() {
		return searchName;
	}
	public void setSearchName(String searchName) {
		this.searchName = searchName;
	}
	
}
